package com.weslide.weslideapp.activity;

import java.util.ArrayList;
import java.util.List;

import net.simonvt.menudrawer.MenuDrawer;
import net.simonvt.menudrawer.Position;

import org.json.JSONException;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gt.cl.http.CLConnectionException;
import com.gt.cl.http.CLInvalidNetworkException;
import com.weslide.weslideapp.R;
import com.weslide.weslideapp.component.MyLinearLayout;
import com.weslide.weslideapp.fragment.GlobalNavigationFragment;
import com.weslide.weslideapp.fragment.LoginFragment;
import com.weslide.weslideapp.fragment.MainFragment;
import com.weslide.weslideapp.fragment.ScoreStoreFragment;
import com.weslide.weslideapp.fragment.WeSlideFragment;
import com.weslide.weslideapp.manager.api.APIManager;
import com.weslide.weslideapp.manager.api.LoginManager;
import com.weslide.weslideapp.pojo.ao.ShopTypeAO;
import com.weslide.weslideapp.pojo.ao.ShopTypeList;
import com.weslide.weslideapp.util.TMTPAsyncTask;

public class MainActivity_de extends WeSlideActivity implements
		OnItemClickListener {

	// private ImageView iv_set;// 图片

	// /** 每次自动展开/收缩的范围 */
	// private int MAX_WIDTH = 0;
	// /** 每次自动展开/收缩的速度 */
	// private final static int SPEED = 30;
	//
	// private final static int sleep_time = 5;
	//
	// private boolean isScrolling = false;
	// private float mScrollX; // 滑块滑动距离
	// private int window_width;// 屏幕的宽度

	// private View view = null;// 点击的view

	// private boolean isMenuShowed = false;
	// private MyLinearLayout mylaout;

	private LinearLayout layout_right;// 右边布局
	private View layout_left;
	private TMTPAsyncTask<Void, Void, Void> async;
	private List<ShopTypeAO> shopTypes = new ArrayList<ShopTypeAO>();
	private ShopTypeList shopTypeListAO;
	private GlobalNavigationFragment globalNavigationFragment;
	private ListView lv_set;// 设置菜单
	private String TAG = "jj";
	private boolean isUserCenter = true;
	public static final String EXTRA_IS_USERCENTER = "extra_is_usercenter";
	private boolean hasMeasured = false;// 是否Measured.
	//
	private RelativeLayout layout_middle;// 左边布局

	//

	private void fetchShopTypes() {
		async = new TMTPAsyncTask<Void, Void, Void>(this, false) {

			@Override
			protected void doOnSuccess(Void result) {
				shopTypes.addAll(shopTypeListAO.getShopTypes());
				myAdapter.notifyDataSetChanged();
			}

			@Override
			protected Void doInBackground(Void params)
					throws CLInvalidNetworkException, CLConnectionException {
				try {
					shopTypeListAO = APIManager.getInstance().getShopTypes();

				} catch (JSONException e) {
					e.printStackTrace();
				}

				return null;
			}
		};
		async.execute();
	}

	private MenuDrawer mMenuDrawer;

	/***
	 * 初始化view
	 */
	void InitView() {
		mMenuDrawer = MenuDrawer.attach(this, MenuDrawer.MENU_DRAG_WINDOW);
		mMenuDrawer.setContentView(R.layout.main);
		mMenuDrawer.setMenuView(R.layout.activity_main_category);
		mMenuDrawer.setTouchMode(MenuDrawer.TOUCH_MODE_NONE);
		// layout_left = findViewById(R.id.layout_left);
		layout_middle = (RelativeLayout) findViewById(R.id.layout_middle);
		// layout_right = (LinearLayout) findViewById(R.id.layout_right);
		// iv_set = (ImageView) findViewById(R.id.iv_set);
		lv_set = (ListView) findViewById(R.id.lv_set);
		// mylaout = (MyLinearLayout) findViewById(R.id.mylaout);
		lv_set.setAdapter(myAdapter);
		lv_set.setOnItemClickListener(this);
		// getMAX_WIDTH();

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// setContentView(R.layout.main);
		InitView();
		if (savedInstanceState == null) {
			getIntent();
			globalNavigationFragment = (GlobalNavigationFragment) getSupportFragmentManager()
					.findFragmentByTag(GlobalNavigationFragment.TAG);
			if (LoginManager.getInstance().isUserLogined()) {
				isUserCenter = getIntent().getBooleanExtra(
						MainActivity_de.EXTRA_IS_USERCENTER, true);
				MainFragment mainFragment = new MainFragment();
				Bundle bundle = new Bundle();
				bundle.putBoolean(EXTRA_IS_USERCENTER, isUserCenter);
				mainFragment.setArguments(bundle);
				globalNavigationFragment.setRootFragment(mainFragment);
			} else {
				globalNavigationFragment.setRootFragment(new LoginFragment());
			}

		}
		// mMenuDrawer.peekDrawer();
		fetchShopTypes();
	}

	public void move() {
		mMenuDrawer.toggleMenu();

		// RelativeLayout.LayoutParams layoutParams =
		// (RelativeLayout.LayoutParams) layout_middle
		// .getLayoutParams();
		// // 左移动
		// if (layoutParams.leftMargin >= 0) {
		// new AsynMove().execute(-SPEED);
		// Log.i(TAG, "speed >>> " + SPEED);
		// lv_set.setSelection(0);// 设置为首位.
		// } else {
		// // 右移动
		// Log.i(TAG, "speed >>> " + SPEED);
		// new AsynMove().execute(SPEED);
		// }
		// new AsynMove().execute(-SPEED);
	}

	/***
	 * 获取移动距离 移动的距离其实就是layout_left的宽度
	 */
	// void getMAX_WIDTH() {
	// ViewTreeObserver viewTreeObserver = layout_middle.getViewTreeObserver();
	// // 获取控件宽度
	// viewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() {
	// @Override
	// public boolean onPreDraw() {
	// if (!hasMeasured) {
	// window_width = getWindowManager().getDefaultDisplay()
	// .getWidth();
	// MAX_WIDTH = layout_right.getWidth();
	// RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
	// layout_middle
	// .getLayoutParams();
	// RelativeLayout.LayoutParams layoutParams_1 =
	// (RelativeLayout.LayoutParams) layout_right
	// .getLayoutParams();
	// ViewGroup.LayoutParams layoutParams_2 = mylaout
	// .getLayoutParams();
	// // 注意： 设置layout_left的宽度。防止被在移动的时候控件被挤压
	// layoutParams.width = window_width;
	// layout_middle.setLayoutParams(layoutParams);
	//
	// // 设置layout_right的初始位置.
	// // layoutParams_1.leftMargin = window_width-100;
	// // layout_right.setLayoutParams(layoutParams_1);
	//
	// // 注意：设置lv_set的宽度防止被在移动的时候控件被挤压
	// layoutParams_2.width = MAX_WIDTH;
	// mylaout.setLayoutParams(layoutParams_2);
	//
	// Log.v(TAG, "MAX_WIDTH=" + MAX_WIDTH + "width="
	// + window_width);
	// hasMeasured = true;
	// }
	// return true;
	// }
	// });
	//
	// }

	// class AsynMove extends AsyncTask<Integer, Integer, Void> {
	//
	// @Override
	// protected Void doInBackground(Integer... params) {
	// int times = 0;
	// if (MAX_WIDTH % Math.abs(params[0]) == 0)// 整除
	// times = MAX_WIDTH / Math.abs(params[0]);
	// else
	// times = MAX_WIDTH / Math.abs(params[0]) + 1;// 有余数
	//
	// Log.i(TAG, "time >>> " + times);
	// for (int i = 0; i < times; i++) {
	// Log.i(TAG, "params >>> " + params[0]);
	// publishProgress(params[0]);
	// try {
	// Thread.sleep(100);
	// } catch (InterruptedException e) {
	// e.printStackTrace();
	// }
	// }
	//
	// return null;
	// }
	//
	// /**
	// * update UI
	// */
	// @Override
	// protected void onProgressUpdate(Integer... values) {
	// RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
	// layout_middle
	// .getLayoutParams();
	// RelativeLayout.LayoutParams layoutParams_1 =
	// (RelativeLayout.LayoutParams) layout_right
	// .getLayoutParams();
	// // 右移动
	// if (values[0] > 0) {
	// layoutParams.leftMargin = Math.min(layoutParams.leftMargin
	// + values[0], 0);
	// layoutParams_1.leftMargin = Math.min(layoutParams_1.leftMargin
	// + values[0], window_width);
	//
	// // Log.v(TAG, "layout_left右" + layoutParams.leftMargin
	// // + ",layout_right右" + layoutParams_1.leftMargin);
	// } else {
	// // 左移动
	// layoutParams.leftMargin =-( Math.min(layoutParams.leftMargin
	// + values[0], -MAX_WIDTH));
	//
	// layoutParams_1.leftMargin = Math.min(layoutParams_1.leftMargin
	// + values[0], window_width - MAX_WIDTH);
	//
	// Log.v(TAG, "layout_middle左" + layoutParams.rightMargin
	// + ",layout_right左" + layoutParams_1.leftMargin);
	//
	//
	// layout_middle.setTranslationX(layoutParams.leftMargin);
	// }
	// // layout_right.setLayoutParams(layoutParams_1);
	//
	// // layout_middle.setLayoutParams(layoutParams);
	//
	// }
	//
	// }

	private BaseAdapter myAdapter = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = getLayoutInflater().inflate(
						R.layout.item_shop_type, null);
				holder.icon = (ImageView) convertView
						.findViewById(R.id.item_shop_type_mImgVIcon);
				holder.typeName = (TextView) convertView
						.findViewById(R.id.item_shop_type_mTvTypeName);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			ShopTypeAO shopTypeAO = shopTypes.get(position);
			holder.typeName.setText(shopTypeAO.getName());
			return convertView;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public int getCount() {
			return shopTypes.size();
		}
	};

	private class ViewHolder {
		ImageView icon;
		TextView typeName;

	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
		// {
		// RelativeLayout.LayoutParams layoutParams =
		// (RelativeLayout.LayoutParams) layout_middle
		// .getLayoutParams();
		// if (layoutParams.leftMargin < 0) {
		// new AsynMove().execute(SPEED);
		// return true;
		// }
		// }
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (!popFragmentFromHistory()) {
				finish();
			}
			return true;
		}

		return super.onKeyUp(keyCode, event);
	}

	public boolean popFragmentFromHistory() {
		if (globalNavigationFragment != null) {
			if (getGlobalNavigationFragmentHistory() > 1) {
				globalNavigationFragment.pop();
				return true;
			}
		} else {

		}
		return false;
	}

	private int getGlobalNavigationFragmentHistory() {
		if (globalNavigationFragment != null) {
			List<String> history = globalNavigationFragment.getHistory();
			if (history != null) {
				return history.size();
			}
		}
		return 0;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_middle
				.getLayoutParams();
		// 只要没有滑动则都属于点击
		// if (layoutParams.leftMargin == -MAX_WIDTH) {
		// move();
		MainFragment mainFragment = ((MainFragment) globalNavigationFragment
				.getCurrentFragment());
		ScoreStoreFragment scoreStoreFragment = ((ScoreStoreFragment) mainFragment
				.getCurrentFragment());
		ShopTypeAO shopTypeAO = shopTypes.get(position);
		scoreStoreFragment.fetchListById(shopTypeAO.getShopTypeId());
		// Toast.makeText(MainActivity_de.this, title[position], 1).show();
		// }

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		WeSlideFragment currentFragment = globalNavigationFragment
				.getCurrentFragment();
		if (currentFragment != null) {
			currentFragment.onActivityResult(requestCode, resultCode, data);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}